<template>
    <div class="add-page">
        <page-head
            class="title_words" 
            checkPlatform="false" 
            :title="title" 
            fColor="#191A1A" 
            style="color: #ffffff;" 
            icon="none" 
            url="/pages/index/index">
            <div slot="icon" @click="handleExit">
                <uni-icons type="closeempty" size="18"></uni-icons>
            </div>
        </page-head>
        <div class="main-content" v-show="!preview" :style="{'background-color': currentStep == 0 ? '#F6F8FC' : '#fff'}">
            <!-- 步骤信息 -->
            <!-- 口语的创建 -->
            <template v-if="examType == 'spoken'">
                <!-- 基本信息 -->
                <base-info ref="baseInfoRef" :modelValue.sync="baseData" v-show="currentStep == 0" :examType="examType"/>
                <div class="spoken" v-show="currentStep != 0">
                    <step :list="steps" :current="currentStep" v-show="currentStep != 0"/>
                    <!-- part1 -->
                    <div class="step-block" v-show="currentStep == 1">
                        <text-block 
                            v-model="spokenModelData['partOne']['content']"
                            title="考试回忆"
                            placeholder="简要描述话题或具体题目，如：Hometown、Study or work等"
                            :height="400"
                            :required="true"
                        />
                        <topic 
                            :modelValue.sync="spokenModelData['partOne']['topics']" 
                            :modelNew.sync="spokenModelData['partOne']['isNewTopic']"
                            dialogTitle="Part 1对应话题（多选）"
                            :Multiple="true"
                            :topicType="1"

                        />
                    </div>
                    <div class="step-block" v-show="currentStep == 2">
                        <!-- part2 -->
                        <text-block 
                            v-model="spokenModelData['partTwo']['content']"
                            title="Part2"
                            placeholder="简要描述核心题干，如：Describe an old person you know and respect..."
                            :height="200"
                            :required="true"
                        />
                        <topic 
                            :modelValue.sync="spokenModelData['partTwo']['topics']" 
                            :modelNew.sync="spokenModelData['partTwo']['isNewTopic']"
                            dialogTitle="Part 2对应话题（单选）"
                            :Multiple="false"
                            :topicType="2"
                        />
                        <!-- part3 -->
                        <text-block 
                            v-model="spokenModelData['partThree']['content']"
                            title="Part3"
                            placeholder="简要描述话题或具体题目，如：不同年龄段人喜欢什么音乐？"
                            :height="200"
                            :required="true"
                        />
                    </div>
                    <!-- 考官信息 -->
                    <div class="step-block no-padding" v-show="currentStep == 3">
                        <examiner :modelValue.sync="examiner"/>
                        <text-block 
                            v-model="examRoom"
                            title="考点信息"
                            placeholder="简要描述考点信息，如：环境等"
                            :height="200"
                            :required="false"
                            :maxLength="100"
                        />
                    </div>
                </div>
            </template>

            <!-- 笔试和机考的创建 -->
            <template v-if="examType != 'spoken'">
                <!-- 基本信息 -->
                <base-info ref="baseInfoRef" :modelValue.sync="baseData" v-show="currentStep == 0" :examType="examType"/>
                <div class="other" v-show="currentStep != 0">
                    <step :list="steps" :current="currentStep" v-show="currentStep != 0"/>

                    <!-- 第一步 -->
                    <div class="step-block" v-show="currentStep == 1">
                        <text-block 
                            v-model="item['content']"
                            :title="item.title"
                            placeholder="简要概括一下考试内容"
                            :height="200"
                            v-for="(item, index) in modelData['partOne']" :key="index"
                        />
                    </div>

                    <!-- 第二步 -->
                    <div class="step-block" v-show="currentStep == 2">
                        <text-block 
                            v-model="item['content']"
                            :title="item.title"
                            placeholder="简要概括一下考试内容"
                            :height="200"
                            v-for="(item, index) in modelData['partTwo']" :key="index"
                        />
                    </div>

                    <!-- 第三步 -->
                    <div class="step-block" v-show="currentStep == 3">
                        <text-block 
                            v-model="item['content']"
                            :uploadUrl.sync="item['imageUrl']"
                            :title="item.title"
                            placeholder="简要概括一下考试内容"
                            :height="200"
                            :upload="item.upload"
                            v-for="(item, index) in modelData['partThree']" :key="index"
                        />
                    </div>
                </div>
            </template>
        </div>

        <!-- 预览 -->
        <div class="preview-warp" v-show="preview">
            <speech-item v-if="examType == 'spoken'" mode="preview" :listData="previewData"/>
            <write-item v-else mode="preview" :listData="previewData"/>
        </div>
        <div class="footer" :style="{'background-color': currentStep > 0 && !preview ? '#fff' : '#F6F8FC'}">
            <div class="back" v-show="currentStep > 0" @click="back"><view class="iconfont icon-back"></view></div>
            <div class="next" @click="next" v-show="currentStep < 3">下一步</div>
            <div class="next" @click="toPreview" v-show="currentStep === 3 && !preview">预览</div>
            <div class="next" @click="publish" v-show="preview">发布</div>
        </div>

        <!-- 保存成功弹窗 -->
        <uni-popup ref="popupRef" background-color="#fff" @change="dialogClose" borderRadius="10px">
            <div class="dialog-content">
                <image class="bg" src="@/static/bg-success.png" alt=""></image>
                <image class="bg" src="@/static/bg-loading.png" alt=""></image>
                <div class="text">
                    <text class="main">{{dialog.title}}</text>
                    <text class="sub">{{dialog.content}}</text>
                </div>
            </div>
        </uni-popup>

        <!-- 退出提示弹窗 -->
        <uni-popup ref="exitPopupRef" background-color="#fff" borderRadius="10px">
            <div class="exit-content">
                <div class="text">
                    <text class="main">温馨提示</text>
                    <text class="sub">退出后您填写的内容将不会保留</text>
                    <text class="sub">您确定退出编辑吗？</text>
                </div>
                <div class="btn">
                    <text class="exit" @click="goBack">退出</text>
                    <text @click="noBack">继续编辑</text>
                </div>
            </div>
        </uni-popup>
        <page-container
            v-if="exitShow"
            :show="true"
            position="bottom"
            :custom-style="`width:0;height:0;`"
            :duration="0"
            :overlay="false"
            :z-index="-1"
            @beforeleave="beforeLeave"
        />
    </div>
</template>

<script>
    import baseInfo from './pages/base-info.vue'
    import Step from './components/step.vue'
    import TextBlock from './components/text-block.vue'
    import topic from './components/topic.vue'
    import Examiner from './components/examiner-info.vue'
    import SpeechItem from '../index/components/speech-item.vue'
    import WriteItem from '../index/components/write-item.vue'
    import { apiWriteSave, apiSpeakSave } from '@/api/memory'
    import examinerData from './components/examiner'
    import {deepCopy} from '@/common/util/util'
    export default {
        options: {
            styleIsolation: 'shared'
        },
        components: {
            baseInfo,
            Step,
            TextBlock,
            topic,
            Examiner,
            SpeechItem,
            WriteItem,
        },
        data(){
            return {
                title: '', // 页面标题
                examType: '', // 回忆类型 spoken口语 write笔试 computer机试
                currentStep: 0,
                baseData: {}, // 通用 基本信息
                // 口语创建的数据---开始
                examiner: {}, // 考官信息
                examRoom: '', // 考点信息
                spokenModelData: {
                    partOne: {title: 'Part1', hasTopic: true},
                    partTwo: {title: 'Part2', hasTopic: true},
                    partThree: {title: 'Part3', hasTopic: false}
                },
                // 口语创建的数据---结束

                // 笔试机试的创建数据---开始
                modelData: {
                    partOne: [
                        {title: 'Section 1', questionType: 1, content: ''},
                        {title: 'Section 2', questionType: 1, content: ''},
                        {title: 'Section 3', questionType: 1, content: ''},
                        {title: 'Section 4', questionType: 1, content: ''},
                    ],
                    partTwo: [
                        {title: 'Passage 1', questionType: 2, content: ''},
                        {title: 'Passage 2', questionType: 2, content: ''},
                        {title: 'Passage 3', questionType: 2, content: ''},
                    ],
                    partThree: [
                        {title: 'Task 1', questionType: 4, content: '', upload: true},
                        {title: 'Task 2', questionType: 4, content: ''},
                    ]
                },
                // 笔试和机试创建的数据---结束

                preview: false, // 预览模式
                routeQuery: {}, // 路由参数
                dialog: { // 保存的弹窗文案
                    title: '',
                    content: ''
                },
                previewData: {},
                user: {},
                exitShow: true // 退出弹窗
            }
        },
        computed: {
            // 步骤条
            steps(){
                const listMap = {
                    spoken: [
                        {title: 'Part1', step: 1},
                        {title: 'Part2&3', step: 2},
                        {title: '考点信息', step: 3},
                    ],
                    other: [
                        {title: '听力', step: 1},
                        {title: '阅读', step: 2},
                        {title: '写作', step: 3},
                    ]
                }
                return listMap[this.examType == 'spoken' ? 'spoken' : 'other']
            },

        },
        onLoad(option){
            this.routeQuery = option
            this.setTitle(option)
            this.examType = option.type
            this.getUserInfo()
            try {
                uni.setStorageSync('select-school', '')
            } catch (e) {
                console.log(e, 'err')
            }
        },
        async onShow(){
            await this.$nextTick()
            this.$refs.baseInfoRef && this.$refs.baseInfoRef.show()
        },
        methods: {
            getUserInfo(){
                this.$store.dispatch('GetUserInfo').then(res => {
                    if(res.code === 200){
                        this.user = res.data
                    }
                })
            },

            // 动态设置创建页标题
            setTitle(option){
                const titleMap = {
                    spoken: '创建口语回忆',
                    write: '创建回忆',
                    computer: '创建回忆',
                }
                this.title = titleMap[option.type]
            },

            // 校验基本信息
            checkBase(){
                return this.$refs.baseInfoRef.validate()
            },

            // 校验第一步 第二步
            /**
             * 
             * @param data 校验的数据
             * @param step 哪一步
             */
            checkPartOne(data, step = 1){
                if(this.examType !== 'spoken') return true
                let pass = true
                const errText = {
                    content: `请填写考试回忆`,
                    topics: '请选择相关话题',
                }
                for (let i = 0; i < data.length; i++) { // foreach无法终止，无法保证执行顺序
                    const item = data[i];
                    for (const key in errText) {
                        if(key === 'content' && !item[key]){
                            if(step === 2){
                                errText['content'] = `请填写${item.title}考试回忆`
                            }
                            this.$tip.toast(errText[key])
                            pass = false
                            return
                        }else if(key === 'topics' && item.hasTopic && (!item[key] || !item[key].length)) {
                            this.$tip.toast(errText[key])
                            pass = false
                            return
                        }
                    }
                }
                return pass
            },

            // 校验最后一步
            checkLast(){
                let pass = true
                if(this.examType == 'spoken'){
                    for (const key in this.examiner) {
                        if(!this.examiner[key]){
                            this.$tip.toast('请选择考官信息')
                            pass = false
                            return
                        }
                    }
                }else {
                    const format = Object.values(this.modelData).flat() || []
                    const result = format.every(item => {
                        return ['content', 'imageUrl'].every(i => !item[i])
                    })
                    if(result){
                        this.$tip.toast('您还未填写回忆内容哦～')
                        pass = false
                    }
                }
                return pass
            },

            // 考点信息展示格式化
            formatTag(field, value){
                const data = {
                    examinerSex: `${value}考官`,
                    examinerSpeed: `语速${value}`,
                    examinerAccent: `${value}`,
                    examinerVolume: `音量${value}`,
                    examinerGuide: `${value}引导`,
                    examinerInterrupt: `${value}打断`,
                    examinerAttitude: `态度${value}`,
                }
                return data[field]
            },

            // 预览
            toPreview(){
                if(this.checkLast()){
                    const obj = {
                        ...this.formatData(),
                        createByNickName: this.user.nickName || '',
                        createByAvatar: this.user.avatar || ''
                    }
                    this.previewData = deepCopy(obj)
                    this.preview = true
                    this.title = '预览'
                }
            },

            // 下一步
            next(){
                const validateFuc = {
                    '0': this.checkBase,
                    1: () => this.checkPartOne([this.spokenModelData.partOne], 1),
                    2: () => this.checkPartOne([this.spokenModelData.partTwo, this.spokenModelData.partThree], 2),
                }
                if(validateFuc[this.currentStep]()){
                    this.currentStep+=1
                }
            },

            // 上一步
            back(){
                if(this.preview){
                    this.setTitle(this.routeQuery)
                    this.preview = false
                }else {
                    if(this.currentStep > 0){
                        this.currentStep-=1
                    }
                }
            },

            // 组装数据
            formatData(){
                let formatData = {}
                if(this.examType === 'spoken'){ // 口语回忆的接口格式
                    let formatExaminer = []
                    examinerData.forEach(item => {
                        for (const key in this.examiner) {
                            if (item.field == key) {
                                const data = item.list.find(i => i.value == item.check)
                                formatExaminer.push(this.formatTag(item.field, data.text))
                            }
                        }
                    })
                    formatData = {
                        ...this.baseData,
                        centerId: this.baseData.school.id,
                        ...this.examiner,
                        examiner: formatExaminer,
                        examRoom: this.examRoom,
                        contentList: Object.values(this.spokenModelData)
                    }
                }else { // 笔试和机考的接口格式
                    formatData = {
                        ...this.baseData,
                        centerId: this.baseData.school.id,
                        contentList: Object.values(this.modelData).flat().filter(i => i.content || (i.upload && i.imageUrl)) || []
                    }
                }
                return formatData
            },

            // 发布
            publish(){
                this.$tip.loading()
                let api = this.examType === 'spoken' ? apiSpeakSave : apiWriteSave
                const data = this.formatData()
                api({...data}).then(res => {
                    if(res.code == 200){
                        if(res.data){
                            this.dialog = {
                                title: '发布成功！',
                                content: '爱分享的孩子至少雅思7分哦～'
                            }
                        }else {
                            this.dialog = {
                                title: '已提交',
                                content: '请您耐心等待系统审核～'
                            }
                        }
                        this.$refs.popupRef.open()
                        this.exitShow = false
                        setTimeout(() => {
                            this.$refs.popupRef.close()
                            this.goBack()
                        }, 2000)
                    }
                }).catch(err => {
                    console.log(err, 'err')
                }).finally(() => {
                    this.$tip.loaded()
                })
            },
            dialogClose(val){
                if(!val){
                    this.goBack()
                }
            },

            // 退出添加页
            async goBack(){
                this.exitShow = false
                setTimeout(async() => {
                    uni.setStorageSync('select-school', '')
                    await this.$nextTick()
                    uni.navigateBack()
                    uni.$emit('refresh')
                }, 300)
            },

            // 左上角关闭按钮
            handleExit(){
                this.$refs.exitPopupRef.open()
            },

            // 继续编辑
            noBack(){
                this.$refs.exitPopupRef.close()
                setTimeout(() => {
                    this.exitShow = true
                }, 500)
            },

            // page-container关闭前回调
            async beforeLeave(){
                this.$refs.exitPopupRef.open()
                await this.$nextTick()
                this.exitShow = false
                setTimeout(() => {
                    this.exitShow = true
                }, 0)
            },
        },
    }
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
    @function toRem($rpx){  //$rpx为需要转换的字号
        @return #{$rpx * 100 / 750 / 4}rem; 
    }
    ::-webkit-scrollbar{
        display: none;
    }
    .add-page{
        display: flex;
        flex-direction: column;
        height: 100%;
        position: relative;
    }
    .main-content,.preview-warp{
        width: 100%;
        flex: 1;
        overflow: auto;
        padding-bottom: toRem(170);
        box-sizing: border-box;
    }
    .preview-warp{
        background-color: #F6F8FC;
        padding: toRem(22) toRem(30) toRem(170);
        
        
    }
    .spoken,.other{
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        max-height: 100%;
        padding: 0 toRem(30);
        .step-block{
            flex: 1;
            overflow: auto;
        }
        .no-padding{
            padding-right: 0;
        }
    }
    .footer{
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        display: flex;
        align-items: center;
        padding: toRem(28) toRem(30) toRem(64);
        box-sizing: border-box;
        .back,.next{
            width: toRem(128);
            height: toRem(78);
            background-color: rgba(253, 69, 61, .15);
            color: #FD453D;
            margin-right: toRem(28);
            border-radius: toRem(39);
            text-align: center;
            line-height: toRem(78);
            font-size: toRem(28);
            .icon-back{
                font-size: 20px;
            }
        }
        .next{
            flex: 1;
            background-color: #FD453D;
            color: #fff;
            margin-right: 0;
        }
    }
    .dialog-content{
        width: toRem(540);
        height: toRem(290);
        padding-top: toRem(130);
        box-sizing: border-box;
        border-radius: toRem(10);
        background: linear-gradient(to right,#fff,#EBFCFC, #F3E3F9);
        .bg{
            width: toRem(446);
            height: toRem(196);
            position: absolute;
            left: 50%;
            top: 0;
            transform: translate(-50%,-50%);
        }
        .text{
            display: flex;
            flex-direction: column;
            align-items: center;
            color: #333;
            font-weight: 600;
            font-size: toRem(38);
            .sub{
                font-size: toRem(28);
                font-weight: 400;
                margin-top: toRem(28);
            }
        }
    }
    .exit-content{
        width: toRem(550);
        height: toRem(330);
        // width: 100%;
        // height: 100%;
        padding: toRem(40) toRem(45);
        box-sizing: border-box;
        border-radius: toRem(10);
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: center;
        .text{
            display: flex;
            align-items: center;
            flex-direction: column;
            color: #999;
            font-size: toRem(28);
            .sub{
                color: #333;
                text-align: center;
                margin-top: toRem(37);
            }
            .sub:last-child{
                margin-top: 0;
            }
        }
        .btn{
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: #fff;
            font-size: toRem(28);
            width: 100%;
            &>text{
                border-radius: toRem(41);
                width: toRem(220);
                height: toRem(82);
                text-align: center;
                line-height: toRem(82);
                background-color: #FD453D;
            }
            .exit{
                background-color: #F6F8FC;
                color: #333;
            }
        }
    }
 
</style>
